package com.zlf.sshtools.portforward;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.Setting;
import com.jcraft.jsch.JSchException;
import com.zlf.sshtools.utils.ConfigUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author zlf
 */
public class PortforwardService {

    private Setting portforwardConfig = ConfigUtils.PORTFORWARD_CONFIG;
    private Map<String, PortforwardChannel> channelMap = new HashMap();

    public List<PortforwardVO> getAll() {
        List<PortforwardVO> rtn = new ArrayList();
        portforwardConfig.getGroups().forEach(groupName -> {
            PortforwardVO vo = portforwardConfig.toBean(groupName, PortforwardVO.class);
            vo.id = groupName;
            rtn.add(vo);
        });
        return rtn;
    }

    public void save(PortforwardVO vo) {
        String group = vo.id;
        if (StrUtil.isBlank(group)) {
            group = RandomUtil.randomString(24);
            vo.id = group;
        }
        portforwardConfig.setByGroup("name", group, vo.name);
        portforwardConfig.setByGroup("remoteHost", group, vo.remoteHost);
        portforwardConfig.setByGroup("remotePort", group, String.valueOf(vo.remotePort));
        portforwardConfig.setByGroup("localPort", group, String.valueOf(vo.localPort));
        portforwardConfig.setByGroup("sshHost", group, vo.sshHost);
        portforwardConfig.setByGroup("sshUser", group, vo.sshUser);
        portforwardConfig.setByGroup("sshPassword", group, vo.sshPassword);
        portforwardConfig.setByGroup("socksProxy", group, vo.socksProxy);
        portforwardConfig.setByGroup("autostart", group, String.valueOf(vo.autostart));
        portforwardConfig.store();
    }

    public void del(String group) {
        portforwardConfig.getGroupedMap().remove(group);
        portforwardConfig.store();
    }

    public void start(String group) throws JSchException {
        PortforwardVO vo = portforwardConfig.toBean(group, PortforwardVO.class);
        PortforwardChannel channel = channelMap.get(group);
        if (channel == null) {
            channel = new PortforwardChannel(vo);
            channelMap.put(group, channel);
        }
        channel.start();
    }

    public void stop(String group) {
        PortforwardVO vo = portforwardConfig.toBean(group, PortforwardVO.class);
        PortforwardChannel channel = channelMap.get(group);
        if (channel == null) {
            return;
        }
        channel.stop();
    }
}
